# Patch for google/appengine/tools/dev_appserver.py
def GetLastState():
  try: from sys import OldState
  except ImportError: pass
  else: return State(OldState[-1])

def RegisterOldState(**state):
  try: os = sys.OldState
  except AttributeError:
    os = sys.OldState = []

  state = state.copy()
  os.append(state)
  return State(state)

class State:
  def __init__(self, kwd):
    self.__dict__ = kwd

def DoInLastState(function, *args, **kwd):
  os = GetLastState()
  if os is not None:
    # Push operating state
    this = RegisterOldState(stdin = sys.stdin,
                            stdout = sys.stdout)

    try:
      sys.stdin = os.stdin
      sys.stdout = os.stdout

      return function(*args, **kwd)

    finally:
      sys.stdin = this.stdin
      sys.stdout = this.stdout

def PDebug():
  from pdb import set_trace
  DoInLastState(set_trace)

def ExecuteCGI(root_path,
               handler_path,
               cgi_path,
               env,
               infile,
               outfile,
               module_dict,
               exec_script=ExecuteOrImportScript,
               register_old_state=RegisterOldState):
  # ...
  register_old_state(module_dict = old_module_dict,
                     builtin     = old_builtin,
                     argv        = old_argv,
                     stdin       = old_stdin,
                     stdout      = old_stdout,
                     env         = old_env,
                     cwd         = old_cwd,
                     file_type   = old_file_type)

  # ...